<?php
namespace app\index\controller;

use app\admin\model\Upload;
use app\index\common\Homebase;

use service\FeishuService;
use service\GuardService;
use service\LadderService;
use think\Cache;
use think\Db;
use think\Exception;
use think\Request;

class Index extends Homebase
{

    public function index(){
        $ladderqrcodeinfo = LadderService::instance()->getqrcode(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));
        //dump($ladderqrcodeinfo);exit;
        //获取门禁二维码信息
        $guardqrcodeinfo = GuardService::instance()->getqrcode(self::$homeuser_info['user_id']);
        //dump($guardqrcodeinfo);exit;
        $unifyqrcode = $ladderqrcodeinfo['enceypted'].LadderService::LGSPLIT.$guardqrcodeinfo;
        //dump($unifyqrcode);exit;
        $this->assign("unifyqrcode",$unifyqrcode);
        $this->assign("ladderqrcodeinfo",$ladderqrcodeinfo);
        //调用jssdk
        $config_parameters = FeishuService::instance()->Getparameters();
        $this->assign("parameters",$config_parameters);
        return $this->fetch();
    }

    public function indexv2(){
        //dump(getimagesize("https://elevatorc.gtcloud.cn/uploads/face/2024/04/07/1712455322343700.jpeg"));exit;
        //dump(FeishuService::instance()->Getparameters());exit;
        /*$dir = ROOT_PATH."application";
        //echo $dir;
        dump($dir);
        $files = getFiles($dir);
        dump($files);exit;*/
        //$uid = "15810217293";
        //$timestamp = "1532934542416";
        //$securityKey = "Qazxsw4321";
        //echo base64_encode(md5($uid.$timestamp.$securityKey));exit;
        /*$img = file_get_contents("https://s1-imfile.feishucdn.com/static-resource/v1/v3_0091_851e324f-fa27-4ac4-a0be-6be227125ecg~?image_size=noop&cut_type=&quality=&format=png&sticker_format=.webp");
        echo base64_encode($img);exit;*/
        /*$user = db("user")->where(['user_id'=>96005618])->find();
        $res = GuardService::instance()->AddPerson($user);
        dump($res);exit;*/
        //dump(GuardService::instance()->Getacclevellists());exit;
        //dump(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));exit;
        $ladderqrcodeinfo = LadderService::instance()->getqrcode(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));
        //dump($ladderqrcodeinfo);exit;
        //获取门禁二维码信息
        $guardqrcodeinfo = GuardService::instance()->getqrcode(self::$homeuser_info['user_id']);
        //dump($guardqrcodeinfo);exit;
        $unifyqrcode = $ladderqrcodeinfo['enceypted'].LadderService::LGSPLIT.$guardqrcodeinfo;
        //dump($unifyqrcode);exit;
        $this->assign("unifyqrcode",$unifyqrcode);
        $this->assign("ladderqrcodeinfo",$ladderqrcodeinfo);
        //调用jssdk
        $config_parameters = FeishuService::instance()->Getparameters();
        $this->assign("parameters",$config_parameters);
        return $this->fetch();
    }

    public function indexv1(){
        //dump(getimagesize("https://elevatorc.gtcloud.cn/uploads/face/2024/04/07/1712455322343700.jpeg"));exit;
        //dump(FeishuService::instance()->GetTicket());exit;
        /*$dir = ROOT_PATH."application";
        //echo $dir;
        dump($dir);
        $files = getFiles($dir);
        dump($files);exit;*/
        //$uid = "15810217293";
        //$timestamp = "1532934542416";
        //$securityKey = "Qazxsw4321";
        //echo base64_encode(md5($uid.$timestamp.$securityKey));exit;
        /*$img = file_get_contents("https://s1-imfile.feishucdn.com/static-resource/v1/v3_0091_851e324f-fa27-4ac4-a0be-6be227125ecg~?image_size=noop&cut_type=&quality=&format=png&sticker_format=.webp");
        echo base64_encode($img);exit;*/
        /*$user = db("user")->where(['user_id'=>96005618])->find();
        $res = GuardService::instance()->AddPerson($user);
        dump($res);exit;*/
        //dump(GuardService::instance()->Getacclevellists());exit;
        //dump(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));exit;
        $ladderqrcodeinfo = LadderService::instance()->getqrcode(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));
        //dump($ladderqrcodeinfo);exit;
        //获取门禁二维码信息
        $guardqrcodeinfo = GuardService::instance()->getqrcode(self::$homeuser_info['user_id']);
        //dump($guardqrcodeinfo);exit;
        $unifyqrcode = $ladderqrcodeinfo['enceypted'].LadderService::LGSPLIT.$guardqrcodeinfo;
        //dump($unifyqrcode);exit;
        $this->assign("unifyqrcode",$unifyqrcode);
        $this->assign("ladderqrcodeinfo",$ladderqrcodeinfo);
        //调用jssdk
        $config_parameters = FeishuService::instance()->Getparameters();
        //dump($config_parameters);exit;
        $this->assign("parameters",$config_parameters);
        return $this->fetch();
    }

    public function getqrcodeinfo(){
        $ladderqrcodeinfo = LadderService::instance()->getqrcode(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));
        //dump($ladderqrcodeinfo);exit;
        //获取门禁二维码信息
        $guardqrcodeinfo = GuardService::instance()->getqrcode(self::$homeuser_info['user_id']);
        //dump($guardqrcodeinfo);exit;
        $unifyqrcode = $ladderqrcodeinfo['enceypted'].LadderService::LGSPLIT.$guardqrcodeinfo;
        $data = ['unifyqrcode'=>$unifyqrcode,'hex_data'=>$ladderqrcodeinfo['hex_data']];
        $this->success('ok', null, $data);
    }

    public function visitor(){
        $state = $this->request->get("state", 1, "intval");
        $type = $this->request->get('type', 0, 'intval');
        $this->assign("state", $state);
        $where = [];
        $wherestr = "";
        $ctime = time();
        if ($state == 1) {
            $where['visitoretime'] = ['>=', $ctime];
            $where['state'] = 1;
        } elseif ($state == 2) {
            $wherestr = "visitoretime < {$ctime} or state = 2";
        }
        $where['user_id|create_byid'] = self::$homeuser_info['user_id'];
        $lists = Db::name('visitor')
            ->where($where)
            ->where($wherestr)
            ->order("id desc")
            ->paginate(3, false, ['type' => 'BootstrapDetailed', 'query' => $this->request->request()])->toArray();
        //echo Db::name('visitor')->getLastSql();exit;
        //dump($lists);exit;
        if($type == 1){
            foreach ($lists['data'] as &$row){
                $row['visitorstime'] = date("Y-m-d H:i",$row['visitorstime']);
            }
            return json($lists);
        }
        $this->assign("lists",$lists);
        return $this->fetch();
    }

    public function cancelvisitor(){
        $id = $this->request->post("id");
        $visitorinfo = Db::name("visitor")->where(['id'=>$id])->find();
        if(empty($visitorinfo)){
            $this->error("非法操作！");
        }
        if(!empty($visitorinfo) && ($visitorinfo['create_byid'] != self::$homeuser_info['user_id'])){
            $this->error("请提交人操作提交操作！");
        }
        try {
            Db::name("visitor")->where(['id'=>$id])->update(['state'=>2]);
            $this->AddsgLogs("取消邀约记录");
        }
        catch (Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success("取消邀约成功！");
    }

    public function addvisitor(){
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            if(empty($data['visitoruname'])){
                $this->error("请输入访客姓名");
            }
            if(empty($data['visitorphone'])){
                $this->error("请输入访客手机号码");
            }
            if(empty($data['visitornum'])){
                $this->error("请输入来访人数");
            }
            //拜访开始时间
            if(empty($data['visitorsdate'])){
                $this->error("请输入拜访开始日期");
            }
            if(empty($data['visitorstime'])){
                $this->error("请输入拜访开始时间");
            }
            $data['visitorstime'] = strtotime($data['visitorsdate']." ".$data['visitorstime']);
            unset($data['visitorsdate']);
            if(empty($data['visitoredate'])){
                $this->error("请输入拜访结束日期");
            }
            if(empty($data['visitoretime'])){
                $this->error("请输入拜访结束时间");
            }
            $data['visitoretime'] = strtotime($data['visitoredate']." ".$data['visitoretime']);
            unset($data['visitoredate']);
            if($data['visitoretime'] < $data['visitorstime']){
                $this->error("拜访结束时间不能小于拜访开始时间");
            }
            if(empty($data['visitorbuilderinfo'])){
                $this->error("请输入楼栋信息，例如：X座X楼");
            }
            if(empty($data['visitor_reason'])){
                $this->error("请输入来访事由");
            }
            //访客码
            $data['visitorkey'] = randSole(6,8);
            //给访客发送短信
            $visitorstime = date("Y-m-d H:i",$data['visitorstime']);
            $uname = self::$homeuser_info['username'];
            $uphone = self::$homeuser_info['mobile'];
            $data['msg_content'] = "尊敬的来宾，您已预约{$visitorstime}到访绿城中国，地址：浙江省杭州市西湖区杭大路1号黄龙世纪广场{$data['visitorbuilderinfo']}。请保存此短信，届时凭二维码 https://elevatorc.gtcloud.cn/xcx/{$data['visitorkey']} 入园，接洽姓名{$uname}，联系电话：{$uphone}。";
            $msg_res = sendmsg($data['visitorphone'],$data['msg_content']);
            if($msg_res['errorcode'] != 1){
                $this->error($msg_res['message']);
            }
            $data['sendmsg_res'] = json_encode($msg_res,304);
            $data['create_time'] = time();
            $data['user_id'] = $data['create_byid'] = self::$homeuser_info['user_id'];
            //dump($data);exit;
            try {
                $res_id = db("visitor")->insertGetId($data);
                if($res_id){
                    Cache::store('redis')->set($data['visitorkey'], $res_id);
                }
                $this->AddsgLogs("新增邀约记录");
            }
            catch (Exception $exception){
                $this->error($exception->getMessage());
            }
            $this->success("登记成功！");
        }
        return $this->fetch();
    }

    public function test(){
        exit;
        //FeishuService::instance()->AddEditDepartment(50040479, "contact.department.updated_v3");
        //exit;
        $userinfo = db('user')->where(['user_id'=>15025615])->find();
        $user = [
            "user_id" => $userinfo['user_id'],
            "mobile" => $userinfo['mobile'],
            "username" => $userinfo['username'],
            "gender" => $userinfo['gender'],
            //"avatar_origin" => $userinfo['avatar_origin'],
            "guardinfo" => "402888ee8e0db12d018e0db1b1930665"
        ];
        if($userinfo['is_jtzb'] == 1){
            $user['department_id'] = $userinfo['department_ids'];
        }
        $res = GuardService::instance()->editUser($user);
        dump($res);exit;
        GuardService::instance()->editUser($userinfo);
        /*$user = [
            "user_id" => 96005618,
            "guardinfo" => "402888ee8e0db12d018e0db1b1930665"
        ];
        dump(GuardService::instance()->EditPersonLevel($user));exit;*/
        //dump(GuardService::instance()->getPersoninfo(15049139));exit;
        //dump(GuardService::instance()->getPersoninfo(96005618));exit;
        //dump(GuardService::instance()->Getacclevellists());exit;
        FeishuService::instance()->AddEditUser(13001137, 'contact.user.created_v3');
        $userinfo = FeishuService::instance()->QueryUser(13001137);
        dump($userinfo);

        exit;
        $config_parameters = FeishuService::instance()->Getparameters();
        //dump($config_parameters);exit;
        $this->assign("parameters",$config_parameters);
        return $this->fetch();exit;
        $faceimglists = db("userfaceimg")->select();
        //dump(ROOT_PATH."/public".);exit;
        foreach ($faceimglists as $row){
            $fileinfo = ROOT_PATH."/public".$row['faceimg_origin'];
            if(file_exists($fileinfo)){
                //$imginfo = getimagesize("https://elevatorc.gtcloud.cn".$row['faceimg_origin']);
                $imginfo = getimagesize($fileinfo);
                if($imginfo[0] > 1080 || $imginfo[1] > 1920 || $imginfo[0] < 480 || $imginfo[1] < 640){
                    dump($imginfo);
                    dump($row);
                    dump("=================");
                }
            }
            else{
                dump("图片不存在");
                dump($row);
                dump("=================");
            }
        }
        exit;
        //dump(getimagesize("https://elevatorc.gtcloud.cn/uploads/face/2024/04/07/1712455322343700.jpeg"));exit;
        return $this->fetch();
    }

    public function face(){
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            if(empty($data['user_id']) || empty($data['faceimg']) || empty($data['faceimgid'])){
                $this->error("请先上传图片！");
            }
            try {
                $userinfo = db('user')->where(['user_id'=>$data['user_id']])->find();
                if(empty($userinfo)){
                    $this->error("请求失败！");
                }
                $data['department_id'] = 3;
                if($userinfo['is_jtzb'] == 1){
                    if(empty($userinfo['guard_department_id'])){
                        $dinfo = Db::name("department")->where(['is_jtzb'=>1])->where(['status'=>1])->where(['department_id'=>['in',$userinfo['department_ids']]])->find();
                        $data['department_id'] = $dinfo['guard_department_id'];
                    }
                    else{
                        $data['department_id'] = $userinfo['guard_department_id'];
                    }
                }
                $data['mobile'] = $userinfo['mobile'];
                $data['username'] = $userinfo['username'];
                $data['gender'] = $userinfo['gender'];
                $data['guardinfo'] = "402888ee8e0db12d018e0db1b1930665";
                if(!empty($userinfo['guardinfo'])){
                    $data['guardinfo'] = $userinfo['guardinfo'];
                }
                //门禁人脸识别
                $res = GuardService::instance()->EditPerson($data);
                //dump($res);exit;
                if($res['code'] != 0){
                    $this->error($res['message']);
                }
                db("user")->where(['user_id'=>$data['user_id']])->update(['face_guard_state'=>1,'faceimg'=>$data['faceimg'],'faceimgid'=>$data['faceimgid']]);
                $delimglists = db("userfaceimg")->where(['user_id'=>$data['user_id']])->where(['id'=>['neq',$data['faceimgid']]])->select();
                foreach ($delimglists as $row){
                    if(!empty($row['faceimg_origin']) && file_exists(ROOT_PATH.'public'.$row['faceimg_origin'])){
                        unlink(ROOT_PATH.'public'.$row['faceimg_origin']);
                        db("userfaceimg")->where(['id'=>$row['id']])->delete();
                    }
                }
            }
            catch (Exception $exception){
                $this->error($exception->getMessage());
            }
            $this->success("上传成功！");
        }
        return $this->fetch();
    }

    public function faceold(){
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            if(empty($data['user_id']) || empty($data['faceimg']) || empty($data['faceimgid'])){
                $this->error("请先上传图片！");
            }
            //更新用户信息
            /*$userinfo = db('user')->where(['user_id'=>$data['user_id']])->find();
            $u_type = 'contact.user.created_v3';
            if(!empty($userinfo)){
                $u_type = 'contact.user.updated_v3';
            }
            FeishuService::instance()->AddEditUser($data['user_id'], $u_type);*/


            //门禁人脸识别
            $res = GuardService::instance()->EditPerson($data);
            //dump($res);exit;
            if($res['code'] != 0){
                $this->error($res['message']);
            }
            db("user")->where(['user_id'=>$data['user_id']])->update(['face_guard_state'=>1,'faceimg'=>$data['faceimg'],'faceimgid'=>$data['faceimgid']]);
            $delimglists = db("userfaceimg")->where(['user_id'=>$data['user_id']])->where(['id'=>['neq',$data['faceimgid']]])->select();
            foreach ($delimglists as $row){
                if(!empty($row['faceimg_origin']) && file_exists(ROOT_PATH.'public'.$row['faceimg_origin'])){
                    unlink(ROOT_PATH.'public'.$row['faceimg_origin']);
                    db("userfaceimg")->where(['id'=>$row['id']])->delete();
                }
            }
            $this->success("上传成功！");
        }
        return $this->fetch();
    }

    public function facenew(){
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            if(empty($data['user_id']) || empty($data['faceimg']) || empty($data['faceimgid'])){
                $this->error("请先上传图片！");
            }
            //门禁人脸识别
            $res = GuardService::instance()->EditPerson($data);
            //dump($res);exit;
            if($res['code'] != 0){
                $this->error($res['message']);
            }
            db("user")->where(['user_id'=>$data['user_id']])->update(['face_guard_state'=>1,'faceimg'=>$data['faceimg'],'faceimgid'=>$data['faceimgid']]);
            $delimglists = db("userfaceimg")->where(['user_id'=>$data['user_id']])->where(['id'=>['neq',$data['faceimgid']]])->select();
            foreach ($delimglists as $row){
                if(!empty($row['faceimg_origin']) && file_exists(ROOT_PATH.'public'.$row['faceimg_origin'])){
                    unlink(ROOT_PATH.'public'.$row['faceimg_origin']);
                    db("userfaceimg")->where(['id'=>$row['id']])->delete();
                }
            }
            $this->success("上传成功！");
        }
        return $this->fetch();
    }

    public function UpHomeImages(){
        $jsonArr = ['status' => 400, 'msg' => 'failed'];
        $thumbimg = trim($this->request->post('myPhoto','','trim'));
        $imgpath = "";
        if (!empty($thumbimg)) {
            //$homeuser_info = Session::get("homeuser_info");
            $path = '/uploads/face/' . date('Y') . '/' . date('m') . '/' . date('d') . '/';
            $_root_path = $_SERVER["DOCUMENT_ROOT"] . $path;
            if (!is_dir($_root_path))// 如果文件上传目录不存在
            {
                mkdir($_root_path, 0777, true);
            }
            $ret = createBase64($thumbimg, $_root_path, time() . mt_rand(100000, 999999));
            if ($ret['state'] !== 1) {
                $jsonArr['msg'] = $ret['err'];
                return json($jsonArr);
            }
            $imgpath = $path . $ret['filename'];
            $image = \think\Image::open($_SERVER["DOCUMENT_ROOT"].$imgpath);
            $image_w = $image->width();
            $image_h = $image->height();
            if($image_w < 480 || $image_h < 640){
                $image->thumb(480, 640,6)->save($_SERVER["DOCUMENT_ROOT"].$imgpath);
                $image = \think\Image::open($_SERVER["DOCUMENT_ROOT"].$imgpath);
            }
            //dump($image->width());
            //dump($image->height());
            //exit;
            $image->thumb(900, 1600)->save($_SERVER["DOCUMENT_ROOT"].$imgpath);
            $image = \think\Image::open($_SERVER["DOCUMENT_ROOT"].$imgpath);
            $image_w = $image->width();
            $image_h = $image->height();
        } else {
            $jsonArr['msg'] = "上传图片为空";
            return json($jsonArr);
        }
        $img_id = db("userfaceimg")->insertGetId(['user_id'=>self::$homeuser_info['user_id'],'faceimg_origin'=>$imgpath,'image_w'=>$image_w,'image_h'=>$image_h,'c_time'=>date("Y-m-d H:i:s")]);
        $jsonArr['status'] = 200;
        $jsonArr['msg'] = $imgpath;
        $jsonArr['img_id'] = $img_id;
        return json($jsonArr);
    }

    public function UpThumbImg()
    {
        $param = Request::instance()->param();//接收宽高参数
        $with  = 900;
        $heig  = 1600;
        if(isset($param['width']) && !empty($param['width'])) {
            $with = $param['width'];
        }
        if(isset($param['height']) && !empty($param['height'])) {
            $heig = $param['height'];
        }
        $up = model("Upload");
        return $up->uploadFileThumb($with, $heig);
    }

    public function testface(){
        return $this->fetch();
    }

    public function vueface(){
        return $this->fetch();
    }

    public function ymt(){
        $ladderqrcodeinfo = LadderService::instance()->getqrcode(FeishuService::instance()->GetUserfloorinfo(self::$homeuser_info['user_id']));
        //dump($ladderqrcodeinfo);exit;
        //获取门禁二维码信息
        $guardqrcodeinfo = GuardService::instance()->getqrcode(self::$homeuser_info['user_id']);
        //dump($guardqrcodeinfo);exit;
        $unifyqrcode = $ladderqrcodeinfo['enceypted'].LadderService::LGSPLIT.$guardqrcodeinfo;
        //dump($unifyqrcode);exit;
        $this->assign("unifyqrcode",$unifyqrcode);
        $this->assign("ladderqrcodeinfo",$ladderqrcodeinfo);
        //调用jssdk
        $config_parameters = FeishuService::instance()->Getparameters();
        $this->assign("parameters",$config_parameters);
        return $this->fetch();
    }

}
